package Utils;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class jdbcutils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

    //文件的读取，只需要读取一次即可拿到这些值 使用静态语句块
    static {
        //创建properties对象集合
        Properties pro = new Properties();
        //加载文件
        try {
            //获取
            //获取src路径下的文件的方式  ClassLoader类加载器
            ClassLoader classLoader = jdbcutils.class.getClassLoader();
            URL resource = classLoader.getResource("JDBC.properties");
            String path = resource.getPath();
            //输出路径
            System.out.println(path);
            pro.load(new FileReader(path));
            /**绝对路径
             *pro.load(new FileReader("D:\\ideaproject\\src\\JDBC.properties"));
             * */
            //获取数据
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            //注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    //释放资源
    public static void close(Statement stmt, Connection conn) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //重载方法
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
